package com.djinfo.work.controller;

import com.alibaba.fastjson.JSONObject;
import com.djinfo.work.common.baidu.ueditor.POIReadExcelToHtml;
import com.djinfo.work.common.baidu.ueditor.PoiHTML;
import com.djinfo.work.service.FileService;
import com.djinfo.work.service.TbDicFileMd5Service;
import com.djinfo.work.util.EqualsUtils;
import com.djinfo.work.util.FTPClientUtil;
import com.djinfo.work.util.FileHtml;
import com.djinfo.work.util.MD5Utils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 资料上传
 *
 * @author wxf
 *
 */
@Controller
@RequestMapping("/multipart-file")
public class FileUploadController {
	private static final Log log = LogFactory.getLog(FileUploadController.class);

	/**
	 * 自动注入
	 */

	@Autowired
	public FileService FileService;
	@Autowired
	public TbDicFileMd5Service tbDicFileMd5Service;

	private static String filepath;
	private static String uploadFileUrlPrefix;
	private static String filepathHtml="fileHtml";
	private static String fileType;
	private static String filelook;
	private  static String openOffice;
	private  static String openOfficeBat;

	private static String host;
	private static int port;
	private static String username;
	private static String password ;
	private static int uesr_ftp;

	public static String getOpenOfficeBat() {
		return openOfficeBat;
	}
	@Value("#{configProperties['upload.file.path.openOfficeBat']}")
	public  void setOpenOfficeBat(String openOfficeBat) {
		this.openOfficeBat = openOfficeBat;
	}

	public static String getOpenOffice() {
		return openOffice;
	}
	@Value("#{configProperties['upload.file.openOffice.path']}")
	public void setOpenOffice(String openOffice) {
		this.openOffice = openOffice;
	}

	public static String getFilelook() {
		return filelook;
	}

	@Value("#{configProperties['upload.file.type.look']}")
	public void setFilelook(String filelook) {
		this.filelook = filelook;
	}

	public static String getFileType() {
		return fileType;
	}

	@Value("#{configProperties['upload.file.type.name']}")
	public void setFileType(String fileType) {
		this.fileType = fileType;
	}

	public String getFilepath() {
		return filepath;
	}

	@Value("#{configProperties['upload.file.path.root']}")
	public void setFilepath(String filepath) {
		this.filepath = filepath;
	}

	@Value("#{configProperties['upload.file.url.prefix']}")
	public void setUploadFileUrlPrefix(String uploadFileUrlPrefix) {
		this.uploadFileUrlPrefix = uploadFileUrlPrefix;
	}
	public static String getHost() {
		return host;
	}
	@Value("#{configProperties['upload.file.path.host']}")
	public  void setHost(String host) {
		this.host = host;
	}
	public static int getPort() {
		return port;
	}
	@Value("#{configProperties['upload.file.path.port']}")
	public  void setPort(int port) {
		this.port = port;
	}

	public static String getUsername() {
		return username;
	}
	@Value("#{configProperties['upload.file.path.username']}")
	public  void setUsername(String username) {
		this.username = username;
	}

	public static String getPassword() {
		return password;
	}
	@Value("#{configProperties['upload.file.path.password']}")
	public  void setPassword(String password) {
		this.password = password;
	}

	public static int getUesr_ftp() {
		return uesr_ftp;
	}
	@Value("#{configProperties['upload.file.path.uesr_ftp']}")
	public  void setUesr_ftp(int uesr_ftp) {
		this.uesr_ftp = uesr_ftp;
	}



	/**
	 * 上传
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/upload.do")
	public Object upload(HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		JSONObject data = new JSONObject();

		Map<String, Object> result = new HashMap<String, Object>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		try {
			FTPClientUtil util = new FTPClientUtil(host,port,username,password,false);
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				Calendar cal = Calendar.getInstance();
				int year = cal.get(Calendar.YEAR);// 获取年份
				int month = cal.get(Calendar.MONTH) + 1;// 获取月份
				int day = cal.get(Calendar.DATE);// 获取日
				int hour = cal.get(Calendar.HOUR);// 小时
				int minute = cal.get(Calendar.MINUTE);// 分
				int second = cal.get(Calendar.SECOND);// 秒
				while (iter.hasNext()) {
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String fileName = file.getOriginalFilename();
						if (fileName.trim() != "") {
							String newfileName = this.newFile(fileName); // 最新的文件名
							String extName = this.extName(fileName); // 后缀
							String path = this.path(newfileName, extName);// 定义上传路径
							getfile(filepath + "/" + year + "/" + month + "/" + day);// 如果文件夹没有，则创建
							getfile(filepath + "/"+ filepathHtml+"/"+ year + "/" + month + "/" + day);// 如果文件夹没有，则创建
							File localFile = new File(filepath + "/" + path);
							String fileMD5 = "";
							if("1".equals(uesr_ftp+"")){
								util.login();
								util.upload("/"+path,file.getInputStream());
							}else{
								file.transferTo(localFile);//上传
								fileMD5= DigestUtils.md5Hex(new FileInputStream(new File(filepath + "/" + path)));  //文件转MD5编码
							}

							//判断文件是否存在
							try {

								String path2 = year + "/" + month + "/" + day + "/" + hour + minute
											+ second + MD5Utils.GetMD5Code(newfileName) + "." + extName;
								//result.put("filepath", this.resultFilepath(extName.toLowerCase(), localFile, path2));// 文件浏览url




								result.put("url", path);
								result.put("realpath" ,uploadFileUrlPrefix+ path);
								result.put("path", "");

							}catch (Exception e){
								e.printStackTrace();
								data.put("resultcode", 203);
								data.put("reason", "文件转换可预览格式失败,将无法预览，请重新上传...");
								data.put("result", result);
							}
							// 返回前台数据 存map
							result.put("name", fileName);  //上传文件名
							result.put("newfileName", newfileName);  //文件名称

							data.put("resultcode", 200);
							data.put("reason", "上传成功");
							data.put("result", result);
							return data;
						}
					}
				}
			}
			data.put("resultcode", 201);
			data.put("reason", "上传文件失败,请重新上传");
			data.put("result", result);
			return data;
		} catch (Exception be) {
			log.error(be.getMessage(),be.getCause());
			be.printStackTrace();
			data.put("resultcode", 201);
			data.put("exception",be.getCause());
			data.put("reason", "上传文件失败,请重新上传");
			data.put("result", result);
			return data;
		}
	}


	/**
	 * 富文本图片上传
	 * @param request
	 * @param response
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/image.do")
	public Object image(HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		JSONObject data = new JSONObject();
		Map<String, Object> result = new HashMap<String, Object>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		try {
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				Calendar cal = Calendar.getInstance();
				int year = cal.get(Calendar.YEAR);// 获取年份
				int month = cal.get(Calendar.MONTH) + 1;// 获取月份
				int day = cal.get(Calendar.DATE);// 获取日
				int hour = cal.get(Calendar.HOUR);// 小时
				int minute = cal.get(Calendar.MINUTE);// 分
				int second = cal.get(Calendar.SECOND);// 秒
				while (iter.hasNext()) {
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String fileName = file.getOriginalFilename();
						if (fileName.trim() != "") {
							getfile(filepath +"/image"+ "/" + year + "/" + month + "/" + day);// 如果文件夹没有，则创建
							String url=	year + "/" + month + "/" + day + "/" + hour + minute + second
									+ MD5Utils.GetMD5Code(newFile(fileName))+"."+extName(fileName);
							File localFile = new File(filepath +"/image"+  "/" +url);
							file.transferTo(localFile);//上传
							data.put("state","SUCCESS");
							data.put("original", hour + minute + second + fileName);
							data.put("size",4252);
							data.put("title",fileName);
							data.put("type",extName(fileName));
							data.put("url",uploadFileUrlPrefix+"/image"+ "/" +url);
						}
					}
				}
			}
		}catch (Exception e){
			data.put("state","error");
			return  data;
		}
		return data;
	}

	/**
	 * 下载
	 *
	 */
	@RequestMapping(value = "/download.do")
	public ModelAndView download(HttpServletRequest request, HttpServletResponse response, String path, String name)
			throws Exception {
		download(request, response, path, "application/octet-stream", name);
		return null;
	}


	/**
	 * 删除文件
	 *
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteFile.do")
	public Boolean deleteFile(String path) {
		try {
			File file= new File(filepath+"/"+path);
			//文件是否存在
			if (file.exists()) {
				System.gc();
				boolean dOrf = file.delete();
			}
		}catch (Exception e){
			return  null;
		}
		return null;
	}




	/**
	 * 返回filepath值   对文件后缀判断
	 * @param extName2
	 * @param localFile
	 * @param path2
	 * @return
	 * @throws IOException
	 */
	public String  resultFilepath(String extName2, File localFile,String path2) throws Exception {
		String filepath="";
		String [] fileTypes=fileType.split(",");
		for(String filetypename:fileTypes){
			if(filetypename.toLowerCase().equals(extName2)){
				String encoding = "utf-8";//new FileCharsetDetector().guestFileEncoding(new FileInputStream(localFile));
				if (StringUtils.isNotBlank(encoding)) {
					String content = FileUtils.readFileToString(localFile, encoding);
					FileUtils.writeStringToFile(localFile, content, "utf-8");
				}
				filepath=uploadFileUrlPrefix+"/"+path2;
				break;
			}
		}
		Integer count=0;
		String [] filelooks=filelook.split(",");
		for(String fileslook:filelooks){
			if(fileslook.toLowerCase().equals(extName2)){
				if(!extName2.equals("pdf")&&!extName2.equals("txt")&&!extName2.equals("html")&&!extName2.equals("xml")) {
					filepath=uploadFileUrlPrefix+"/"+filepathHtml+"/"+newFile(path2)+".html";
					getfile(this.filepath+"/"+filepathHtml+"/image/");// 如果文件夹没有，则创建
					getfile(this.filepath+"/"+filepathHtml);// 如果文件夹没有，则创建
					if(extName2.equals("doc")){
						PoiHTML.docToHtml(this.filepath+path2,this.filepath+"/"+filepathHtml+"/"+newFile(path2)+".html",this.filepath+"/"+filepathHtml+"/",uploadFileUrlPrefix+"/"+filepathHtml+"/");
					}else if(extName2.equals("docx")){
						PoiHTML.docxToHtml(this.filepath+path2,this.filepath+"/"+filepathHtml+"/"+newFile(path2)+".html",this.filepath+"/"+filepathHtml+"/",uploadFileUrlPrefix+"/"+filepathHtml+"/");
					}else if(extName2.equals("xlsx")||extName2.equals("xls")){
						POIReadExcelToHtml.importHtml(this.filepath+path2,this.filepath+"/"+filepathHtml+"/"+newFile(path2)+".html");
					}
				}else {
					filepath =uploadFileUrlPrefix+"/"+ path2;
				}
				count = 1;
				break;
			}
		}
		if(count==0){
			filepath="";
		}
		return filepath;
	}




	/**
	 * 返回path
	 * @param newfileName
	 * @param extName
	 * @return
	 */
	public String path(String newfileName,String extName){
		String path="" ;
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);// 获取年份
		int month = cal.get(Calendar.MONTH) + 1;// 获取月份
		int day = cal.get(Calendar.DATE);// 获取日
		int hour = cal.get(Calendar.HOUR);// 小时
		int minute = cal.get(Calendar.MINUTE);// 分
		int second = cal.get(Calendar.SECOND);// 秒
		newfileName=MD5Utils.GetMD5Code(newfileName);
		if (extName.equals("")) {
			path = year + "/" + month + "/" + day + "/" + hour + minute + second
					+newfileName ;
		} else {
			path = year + "/" + month + "/" + day + "/" + hour + minute + second
					+ newfileName + "." + extName;
		}
		return path;
	}

	/**
	 * 获取最新的文件名newFile
	 * @param fileName
	 * @return
	 */
	public String newFile(String fileName){
		String newfileName="";
		if ((fileName != null) && (fileName.length() > 0)) {
			int dot = fileName.indexOf('.');
			if ((dot > -1) && (dot < (fileName.length()))) {
				newfileName = fileName.substring(0, fileName.indexOf("."));
			}
		}
		return newfileName;
	}


	/**
	 * 获取后缀名
	 * @param fileName
	 * @return
	 */
	public String extName(String fileName){
		String extName="";
		if ((fileName != null) && (fileName.length() > 0)) {
			int dot = fileName.lastIndexOf('.');
			if ((dot > -1) && (dot < (fileName.length()))) {
				extName = fileName.substring(fileName.lastIndexOf(".") + 1);
			}
		}
		return extName;
	}


	/**
	 * 创建文件夹
	 * @param filepath
	 */
	public void getfile(String filepath) {
		File yearfile = new File(filepath);
		// 如果文件夹不存在则创建
		if (!yearfile.exists() && !yearfile.isDirectory()) {
			yearfile.mkdirs();
		}
	}



	/**
	 * 下载
	 * @param request
	 * @param response
	 * @param storeName
	 * @param contentType
	 * @param realName
	 * @throws Exception
	 */
	public static void download(HttpServletRequest request, HttpServletResponse response, String storeName,
								String contentType, String realName) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		String downLoadPath = filepath + storeName;

		long fileLength = new File(downLoadPath).length();

		response.setContentType(contentType);
		response.setHeader("Content-disposition",
				"attachment; filename=\"" + new String(realName.getBytes("UTF-8"), "ISO8859-1") + "\"");
		response.setHeader("Content-Length", String.valueOf(fileLength));
		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead = 0;
		while ((bytesRead = bis.read(buff, 0, buff.length)) != -1) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}



//	public static String getText(File file)throws Exception{
//		boolean sort=false;
//		int startPage=1;
//		int endPage=10;
//		PDDocument document=null;
//		try{
//			try{
//				document=PDDocument.load(file);
//			}catch(MalformedURLException e){
//
//			}
//			PDFTextStripper stripper=new PDFTextStripper();
//			stripper.setSortByPosition(sort);
//			stripper.setStartPage(startPage);
//			stripper.setEndPage(endPage);
//			return stripper.getText(document);
//		}catch(Exception e){
//			e.printStackTrace();
//			return "";
//		}finally{
//			if(document!=null){
//				document.close();
//			}
//		}
//	}
//	@ResponseBody
//	@RequestMapping(value = "/name.do")
//	public JSONObject name(){
//		JSONObject  json=new JSONObject();
//		File file=new File("D:\\《代码整洁之道(中文完整版)[韩磊 译]》(1).pdf");
//		try{
//			String cont=getText(file);
//			System.out.println(cont);
//			json.put("cont" ,cont);
//			return  json;
//		}catch(Exception e){
//			return  json;
//		}
//	}



}